﻿using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace Common.Extentions
{
    public static class Crypt
    {
        static readonly byte[] Bytes = Encoding.ASCII.GetBytes("ZeroCool");
        /// <summary>
        /// Encrypts the specified original string.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string Encrypt(object value)
        {
            var cryptoProvider = new DESCryptoServiceProvider();
            var memoryStream = new MemoryStream();
            var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(Bytes, Bytes), CryptoStreamMode.Write);

            var writer = new StreamWriter(cryptoStream);
            writer.Write(value);
            writer.Flush();
            cryptoStream.FlushFinalBlock();
            writer.Flush();

            return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
        }

        /// <summary>
        /// Decrypt a crypted string.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>
        /// The decrypted string.
        /// </returns>
        public static string Decrypt(object value)
        {
            var cryptoProvider = new DESCryptoServiceProvider();
            var memoryStream = new MemoryStream(Convert.FromBase64String(value.ToString()));
            var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(Bytes, Bytes), CryptoStreamMode.Read);
            var reader = new StreamReader(cryptoStream);

            return reader.ReadToEnd();
        }
    }
}